import logging
import random

logger = logging.getLogger('django')
from django.http import HttpResponse, JsonResponse
from django.views import View
from django_redis import get_redis_connection
from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import ccp_send_sms_code


#图形验证码
class ImageCodeView(View):
    def get(self,request,uuid):
        text,image = captcha.generate_captcha()
        """拆包生成text和图形验证码"""
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s'%uuid,300,text)

        return HttpResponse(image,content_type='image/jpg')


# 短信验证码
class SMSCodeView(View):
    def get(self,request,mobile):
        # 1.接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 2.校验参数
        if not all([image_code_client,uuid]):
            return JsonResponse({
                'code':400,
                "errmsg":"缺少必要参数"
            })
        # 3.创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')
        # 4.提取图形验证码
        image_code_server = redis_conn.get('img_%s'%uuid)
        if image_code_server is None:
            return JsonResponse({
                'code':400,
                'errmsg':'图形验证码失效'
            })
        # 5.对比图形验证码
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return JsonResponse({
                'code':400,
                'errmsg':'输入图形验证码有误'
            })
        # 6.删除验证码，避免恶意测试
        try:
            redis_conn.delete('img_%s'%uuid)
        except Exception as e:
            logger.error(e)
        # 7.生成短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        print(sms_code)
        logger.info(sms_code)
        """
        # 8.临时存储验证码
        redis_conn.setex('sms_%s')%mobile,300,sms_code
        # 9.发送短信验证码
        CCP().send_template_sms(mobile,[sms_code,5],1)
        """
        #异步任务执行写法
        conn = get_redis_connection('sms_code')
        p1 = conn.pipeline()
        p1.setex('sms_code%s'%mobile,300,sms_code)
        p1.setex('send_flag_%s'%mobile,60,1)
        p1.execute()

        ccp_send_sms_code.delay(mobile,sms_code)
        # 10.响应结果
        return JsonResponse({
            'code':0,
            'errmsg':'发送短信成功'
        })

